package com.yjh.common.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Component
public class FileUploadUtil {
    @Value("${playbook.basePath}")
    private String basePath;
    @Value("${playbook.accessPath}")
    private String accessPath;

//    多个文件上传
    public String uploadFiles(List<MultipartFile> files)throws IOException{
        List<String> courtImg=new ArrayList<>();

        if (files == null || files.isEmpty()) {
            return "空文件";
        }

        for(MultipartFile file:files){
//            把url塞进list里面
            courtImg.add(uploadSingleFile(file));
        }

        return String.join(",",courtImg);
    }

//    单个文件上传
    public String uploadFile(MultipartFile file)throws IOException{
        if (file == null || file.isEmpty()) {
            return "空文件";
        }
        return uploadSingleFile(file);
    }

//    处理文件核心逻辑
    private String uploadSingleFile(MultipartFile file) throws IOException{
        String originalFilename = file.getOriginalFilename();
        String suffix=originalFilename.substring(originalFilename.lastIndexOf("."));

        String fileName= UUID.randomUUID().toString()+suffix;

        String absoluteBasePath = FilePathUtil.getAbsolutePath(basePath);
        File dir = new File(absoluteBasePath, fileName);

        //若该目录不存在
        if(!dir.getParentFile().exists()){ dir.getParentFile().mkdirs();}

        //将MultipartFile转存为本地文件
        file.transferTo(dir);

        //传入数据库并给到前端
        return accessPath + fileName;
    }

    public boolean deleteImgByUrl(String fileUrl) {
        try {
            // 从URL中提取文件名
            String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
            String absoluteBasePath = FilePathUtil.getAbsolutePath(basePath);
            File fileToDelete = new File(absoluteBasePath, fileName);

            return fileToDelete.exists() && fileToDelete.delete();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    //批量删除图片（编辑时删除多个旧图）
    public void deleteImgsByUrls(List<String> imgUrls) {
        for (String url : imgUrls) {
            deleteImgByUrl(url); // 循环删除每个图片
        }
    }
}
